<template>
  <HomePage
    v-if="currentView === 'home'"
    :achievements="achievements"
    :activeTab="activeTab"
    :onStartTest="handleStartTest"
    :onTabChange="setActiveTab"
    :testResults="testResults"
    :userProfile="userProfile"
  ></HomePage>
  <div
    v-else
    class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50"
  >
    <header
      class="border-b bg-white/70 backdrop-blur-xl sticky top-0 z-50 shadow-sm"
    >
      <div class="container mx-auto px-4 py-4">
        <div class="flex items-center justify-between min-h-[40px]">
          <div class="flex items-center gap-4">
            <Motion
              :whileHover="{ scale: 1.05 }"
              :whileTap="{ scale: 0.95 }"
              class="flex items-center"
            >
              <Button
                class="flex items-center gap-2 h-8 px-3 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
                size="sm"
                variant="ghost"
                @click="
                  () => {
                    currentView = 'home';
                    activeTab = 'tests';
                  }
                "
              >
                <Home class="w-4 h-4 flex-shrink-0" />
                <span class="leading-none">{{ t('indexPage.home') }}</span>
              </Button>
            </Motion>
            <div class="h-5 w-px bg-slate-200 flex-shrink-0" />
            <h1
              class="text-lg font-semibold bg-gradient-to-r from-slate-700 to-slate-900 bg-clip-text text-transparent leading-none flex items-center"
            >
              {{
                currentView === "dashboard"
                  ? t('indexPage.dashboard')
                  : currentView === "profile"
                  ? t('indexPage.profile')
                  : currentView === "ai-battle"
                  ? t('indexPage.aiBattleMode')
                  : tests.find((t) => t.id === currentView)?.title
              }}
            </h1>
          </div>
          <div class="flex items-center gap-3">
            <Motion
              :transition="{ duration: 0.2 }"
              :whileHover="{ scale: 1.05 }"
              class="flex items-center"
            >
              <Badge
                class="flex items-center gap-1.5 h-8 px-3 bg-gradient-to-r from-orange-100 to-red-100 text-orange-700 border-orange-200 hover:shadow-sm transition-all duration-200"
                variant="secondary"
              >
                <Flame class="w-3 h-3 flex-shrink-0" />
                <span class="leading-none whitespace-nowrap">
                  {{ t('indexPage.streak', { days: calculateStreakDays(testResults) }) }}
                </span>
              </Badge>
            </Motion>
            <Motion
              :transition="{ duration: 0.2 }"
              :whileHover="{ scale: 1.05 }"
              class="flex items-center"
            >
              <Badge
                class="flex items-center gap-1.5 h-8 px-3 bg-gradient-to-r from-purple-50 to-indigo-50 text-purple-700 border-purple-200 hover:shadow-sm transition-all duration-200"
                variant="outline"
              >
                <Star class="w-3 h-3 flex-shrink-0" />
                <span class="leading-none whitespace-nowrap">
                  {{ t('indexPage.level', { level: userProfile.level }) }}
                </span>
              </Badge>
            </Motion>
          </div>
        </div>
      </div>
    </header>

    <main class="container mx-auto px-8 py-6">
      <Motion
        :animate="{ opacity: 1, y: 0 }"
        :initial="{ opacity: 0, y: 20 }"
        :transition="{ duration: 0.5, ease: 'easeOut' }"
      >
        <component :is="renderTestComponent" />
      </Motion>
    </main>
  </div>
</template>

<script setup>
import { computed, ref, watch, h } from "vue";
import { Motion } from "motion-v"; // 修正后的动画组件
import { Flame, Home, Star } from "lucide-vue-next";
import Button from "../components/Button.vue";
import Badge from "../components/badge.vue";
import HomePage from "../pages/HomePage.vue";
import { getInitialAchievements, getTests, getTestCategories } from "../constants/tests.js";
import {
  calculateStreakDays,
  checkAchievements,
  updateUserStats,
} from "../utils/aceievements.js";
import ReactionTimeTest from "~/components/ReactionTimeTest.vue";
import TypingSpeedTest from "~/components/TypingSpeedTest.vue";
import MemoryTest from "~/components/MemoryTest.vue";
import AttentionTest from "~/components/AttentionTest.vue";
import CoordinationTest from "~/components/CoordinationTest.vue";
import ColorTest from "~/components/ColorTest.vue";
import MathTest from "~/components/MathTest.vue";
import LogicalReasoningTest from "~/components/LogicalReasoningTest.vue";
import VisualPerceptionTest from "~/components/VisualPerceptionTest.vue";
import WorkingMemoryTest from "~/components/WorkingMemoryTest.vue";
import SpatialReasoningTest from "~/components/SpatialReasoningTest.vue";
import PatternRecognitionTest from "~/components/PatternRecognitionTest.vue";
import AIBattleMode from "~/components/AIBattleMode.vue";
import DigitMemoryTest from "~/components/DigitMemoryTest.vue";
import TimePerceptionTest from "~/components/TimePerceptionTest.vue";
import ConceptFormationTest from "~/components/ConceptFormationTest.vue";
import DecisionMakingTest from "~/components/DecisionMakingTest.vue";
import ProcessingSpeedTest from "~/components/ProcessingSpeedTest.vue";
import InhibitoryControlTest from "~/components/InhibitoryControlTest.vue";
import ReadingComprehensionTest from "~/components/ReadingComprehensionTest.vue";
import CognitiveFlexibilityTest from "~/components/CognitiveFlexibilityTest.vue";
import MultitaskTest from "~/components/MultitaskTest.vue";
import EmotionRecognitionTest from "~/components/EmotionRecognitionTest.vue";
import SpatialMemoryTest from "~/components/SpatialMemoryTest.vue";
import AudioMemoryTest from "~/components/AudioMemoryTest.vue";
import VerbalFluencyTest from "~/components/VerbalFluencyTest.vue";
import WordAssociationTest from "~/components/WordAssociationTest.vue";
import CreativeThinkingTest from "~/components/CreativeThinkingTest.vue";
import CriticalThinkingTest from "~/components/CriticalThinkingTest.vue";
import SequenceReasoningTest from "~/components/SequenceReasoningTest.vue";
import AbstractReasoningTest from "~/components/AbstractReasoningTest.vue";
import ProfilePage from "~/components/ProfilePage.vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 状态管理
const currentView = ref("home");
const activeTab = ref("tests");
const testResults = ref([]);
const userProfile = ref({
  name: t('indexPage.testUser'),
  age: 25,
  level: 1,
  totalTests: 0,
  averageScore: 0,
  badges: [],
  streak: 0,
  joinDate: new Date(),
});

const tests = computed(() => getTests(t));
const testCategories = computed(() => getTestCategories(t));
const achievements = ref(getInitialAchievements(t));

const handleTestComplete = (result) => {
  const enhancedResult = {
    ...result,
    percentile: Math.max(
      1,
      Math.min(99, result.score + Math.random() * 20 - 10)
    ),
    date: new Date().toISOString(), // 添加日期字段以便跟踪
  };

  // Vue 使用 .value 访问 ref 的值
  testResults.value = [...testResults.value, enhancedResult];

  // 更新 activeTab 和 currentView
  activeTab.value = result.details?.battleMode ? "ai-battle" : "dashboard";
  currentView.value = "home";
  console.log("activeTab.value", activeTab.value);
};

const handleStartTest = (testType) => {
  console.log("value", testType);
  if (testType === "home") {
    currentView.value = "home";
    activeTab.value = "tests";
  } else {
    currentView.value = testType;
  }
};
const setActiveTab = (value) => {
  activeTab.value = value;
};

const onBack = () => {
  currentView.value = "home";
  activeTab.value = "ai-battle";
};

const setUserProfile = (value) => {
  userProfile.value = value;
};

// 组件动态加载
const renderTestComponent = computed(() => {
  switch (currentView.value) {
    case "reaction":
      return h(ReactionTimeTest, {
        onComplete: handleTestComplete,
      });
    case "typing":
      return h(TypingSpeedTest, {
        onComplete: handleTestComplete,
      });
    case "memory":
      return h(MemoryTest, {
        onComplete: handleTestComplete,
      });
    case "attention":
      return h(AttentionTest, {
        onComplete: handleTestComplete,
      });
    case "coordination":
      return h(CoordinationTest, {
        onComplete: handleTestComplete,
      });
    case "color":
      return h(ColorTest, {
        onComplete: handleTestComplete,
      });
    case "math": //有问题！！！！！！！！！！！！！！！！！
      return h(MathTest, {
        onComplete: handleTestComplete,
      });
    case "logical":
      return h(LogicalReasoningTest, {
        onComplete: handleTestComplete,
      });
    case "visual":
      return h(VisualPerceptionTest, {
        onComplete: handleTestComplete,
      });
    case "working-memory":
      return h(WorkingMemoryTest, {
        onComplete: handleTestComplete,
      });
    case "spatial-reasoning":
      return h(SpatialReasoningTest, {
        onComplete: handleTestComplete,
      });
    case "pattern-recognition":
      return h(PatternRecognitionTest, {
        onComplete: handleTestComplete,
      });
    case "home":
      return h(HomePage, {
        testResults: testResults.value,
        userProfile: userProfile.value,
        achievements: achievements.value,
        onStartTest: handleStartTest,
        activeTab: activeTab.value,
        onTabChange: setActiveTab,
      }); // 直接返回组件引用
    case "ai-battle":
      return h(AIBattleMode, {
        onComplete: handleTestComplete,
        onBack: onBack,
      });
    case "digit-memory":
      return h(DigitMemoryTest, {
        onComplete: handleTestComplete,
      });
    case "time-perception":
      return h(TimePerceptionTest, {
        onComplete: handleTestComplete,
      });
    case "concept-formation":
      return h(ConceptFormationTest, {
        onComplete: handleTestComplete,
      });
    case "decision-making":
      return h(DecisionMakingTest, {
        onComplete: handleTestComplete,
      });
    case "processing-speed":
      return h(ProcessingSpeedTest, {
        onComplete: handleTestComplete,
      });
    case "spatial-memory":
      return h(SpatialMemoryTest, {
        onComplete: handleTestComplete,
      });
    case "audio-memory":
      return h(AudioMemoryTest, {
        onComplete: handleTestComplete,
      });
    case "verbal-fluency":
      return h(VerbalFluencyTest, {
        onComplete: handleTestComplete,
      });
    case "emotion-recognition":
      return h(EmotionRecognitionTest, {
        onComplete: handleTestComplete,
      });
    case "word-association":
      return h(WordAssociationTest, {
        onComplete: handleTestComplete,
      });
    case "critical-thinking":
      return h(CriticalThinkingTest, {
        onComplete: handleTestComplete,
      });
    case "sequence-reasoning":
      return h(SequenceReasoningTest, {
        onComplete: handleTestComplete,
      });
    case "abstract-reasoning":
      return h(AbstractReasoningTest, {
        onComplete: handleTestComplete,
      });
    case "creative-thinking":
      return h(CreativeThinkingTest, {
        onComplete: handleTestComplete,
      });
    case "multitask":
      return h(MultitaskTest, {
        onComplete: handleTestComplete,
      });
    case "inhibitory-control":
      return h(InhibitoryControlTest, {
        onComplete: handleTestComplete,
      });
    case "cognitive-flexibility":
      return h(CognitiveFlexibilityTest, {
        onComplete: handleTestComplete,
      });
    case "reading-comprehension":
      return h(ReadingComprehensionTest, {
        onComplete: handleTestComplete,
      });
    case "profile":
      return h(ProfilePage, {
        onUpdateProfile: setUserProfile,
        achievements: achievements.value,
        testResults: testResults.value,
        userProfile: userProfile.value,
      });
    default:
      return null;
  }
});

watch(
  () => testResults.value,
  () => {
    const statsUpdate = updateUserStats(testResults.value);
    userProfile.value = { ...userProfile.value, ...statsUpdate };
    achievements.value = checkAchievements(
      testResults.value,
      achievements.value,
      tests.value,
      testCategories.value
    );
  }
);
</script>